import os
import subprocess
import sys
from pathlib import Path
from PIL import Image

import PySimpleGUI as sg

# 修复高DPI感知
if sys.platform == 'win32':
    try:
        import ctypes

        ctypes.OleDLL('shcore').SetProcessDpiAwareness(1)
    except (ImportError, AttributeError, OSError):
        pass

layout = [
    # 目录选择
    [sg.Text('选择目录'), sg.Input(key='-DIR-', default_text=os.getcwd()), sg.FolderBrowse('浏览'), sg.Button('检索')],
    [sg.Listbox(values=[], size=(67, 10), key='-LIST-')],
    [sg.Text('图像质量'),
     sg.Slider(range=(10, 100), default_value=80, resolution=5, orientation='h', key='-QUALITY-', size=(50, 20))],
    [sg.Text('尺寸比例'),
     sg.Slider(range=(10, 100), default_value=100, resolution=5, orientation='h', key='-RATIO-', size=(50, 20))],
    [
        sg.Button('打开'),
        sg.Button('位置'),
        sg.Button('压缩', button_color=('black', 'yellow')),
        sg.Button('关闭')
    ]
]

window = sg.Window('图片批量压缩为JPG', layout)

while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED or event == '关闭':
        break
    elif event == '检索':
        try:
            dir_path = values['-DIR-']

            img_list = [*Path(dir_path).glob('*.jpg'), *Path(dir_path).glob('*.png')]
            window['-LIST-'].update(img_list)
        except FileNotFoundError:
            sg.popup_quick('目录不存在')
    elif event == '打开':
        try:
            sel_img = values['-LIST-'][0]
            subprocess.run(['explorer', sel_img])
        except IndexError:
            sg.popup_quick('请选择一张图片')
    elif event == '位置':
        try:
            sel_img = values['-LIST-'][0]
            # 使用explorer /select打开文件位置
            subprocess.run(['explorer', f'/select,{sel_img}'])
        except IndexError:
            sg.popup_quick('请选择一张图片')
    elif event == '压缩':
        # 使用pillow打开并压缩图片，质量为-QUALITY-的值
        if img_list:
            for x in img_list:
                with Image.open(x) as im:
                    size_ratio = values['-RATIO-'] / 100
                    if size_ratio != 1:
                        print('调整尺寸 ', x)
                        im = im.resize((int(im.width * size_ratio), int(im.height * size_ratio)))
                    new_dir = x.parent / 'new'
                    new_dir.mkdir(parents=True, exist_ok=True)
                    new_path = new_dir / x.name
                    quality = int(values['-QUALITY-'])
                    print(f'压缩质量 {quality}')
                    im.convert("RGB").save(new_path, quality=quality, optimize=True)
                    print(f'{x}压缩成功')
        else:
            sg.popup_quick('请选择目录')

window.close()
